package com.hospicpc.demos.ws;


import com.hospicpc.demos.config.GetHttpSessionConfig;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import sun.misc.MessageUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfig.class)
@Component
public class ChatEndPoint {

    private final static Map<String,Session> onLineUsers = new ConcurrentHashMap<>();
    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        //获取httpSession并保存
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpRequest.class.getName());
        String user = (String)this.httpSession.getAttribute("user");
        onLineUsers.put(user,session);
        //广播消息，将所有登录用户推送给所有用户

    }

    private void broadcastAllUsers(String message) {
        Set<Map.Entry<String, Session>> entries = onLineUsers.entrySet();
        for (Map.Entry<String, Session> entry : entries) {
            Session session = entry.getValue();
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnMessage
    public void onMessage(String message) {

    }

    @OnClose
    public void onClose(Session session) {

    }
}
